#include "stdafx.h"
#include "jfile.h"

#include "directui.h"

#include <gtl/script/jscript.h>
#include <gtl/directui/visitor.h>

namespace gtl
{

namespace dui
{

jfile::jfile(const std::vector<gtl::tstr>& args)
{
	if(args.size() >= 2)
		m_file.open(args[0], args[1]);
}

jfile::~jfile()
{
}

v8::Handle<v8::Value> jfile::open(const v8::Arguments& args)
{
	if(args.Length() < 2)
		return v8::False();

	gtl::tstr path(gtl::jscript::cstr(args, 0));
	if(path.empty())
		return v8::False();

	gtl::tstr mode(gtl::jscript::cstr(args, 1));
	if(mode.empty())
		mode = _T("r");

	if(m_file.open(path, mode))
		return v8::True();

	return v8::False();
}

v8::Handle<v8::Value> jfile::close(const v8::Arguments& args)
{
	m_file.close();
	return v8::Undefined();
}

v8::Handle<v8::Value> jfile::length(const v8::Arguments& args)
{
	return v8::Integer::New(m_file.length());
}

v8::Handle<v8::Value> jfile::size(const v8::Arguments& args)
{
	return v8::Integer::New(m_file.size());
}

v8::Handle<v8::Value> jfile::tell(const v8::Arguments& args)
{
	return v8::Integer::New(m_file.tell());
}

v8::Handle<v8::Value> jfile::seek(const v8::Arguments& args)
{
	return v8::Integer::New(0);
}

v8::Handle<v8::Value> jfile::read(const v8::Arguments& args)
{
	__int64 size = 0;
	if(args.Length() > 0)
		size = gtl::jscript::cstr(args, 0).cast<__int64>();

	if(size <= 0)
		size = m_file.size();

	if(size <= 0)
		return v8::String::New("");

	gtl::str data;
	data.resize(size + 1);
	m_file.read(data.data(), size);

	return v8::String::New(data.utf8().c_str());
}

v8::Handle<v8::Value> jfile::read_line(const v8::Arguments& args)
{
	return v8::Integer::New(0);
}

v8::Handle<v8::Value> jfile::write(const v8::Arguments& args)
{
	if(args.Length() <= 0)
		return v8::False();

	gtl::str data(gtl::jscript::cstr(args, 0));
	m_file.write(data.c_str(), data.size());

	return v8::True();
}

v8::Handle<v8::Value> jfile::eof(const v8::Arguments& args)
{
	if(m_file.eof())
		return v8::True();

	return v8::False();
}

} // end of namespace dui

} // end of namespace gtl
